Importing Required Libraries for the Flask Prediction App
import requests
import joblib
import pandas as pd
from flask import Flask, request, jsonify, render_template
from datetime import datetime, timedelta
Line-by-Line Explanation
import requests
Imports the requests library, used for making HTTP requests to external APIs (e.g., retrieving match or team data from an online source).
import joblib
Imports the joblib library, which is typically used to load previously saved machine learning models or scalers in `.pkl` format.
import pandas as pd
Imports the Pandas library and assigns it the alias pd. It is used for data manipulation, especially DataFrames, which are useful for organizing feature data before prediction.
from flask import Flask, request, jsonify, render_template
Imports the core components of Flask:
Flask: the class to instantiate the web application.
request: to access data sent by the client (e.g., form or JSON data).
jsonify: to convert Python dictionaries into JSON responses.
render_template: to render HTML pages (useful for displaying results in a web interface).
from datetime import datetime, timedelta
Imports datetime and timedelta from Python’s standard datetime module. These are used to handle and manipulate date and time values, for example: to compare dates, format them, or calculate future/past intervals.
API-Football Configuration
# ==========================
# API-Football Configuration
# ==========================
API_KEY = "d294c3b78ccc4d7f858fc8f07d0496b8"
API_BASE_URL = "https://v3.football.api-sports.io"
HEADERS = {"x-apisports-key": API_KEY}
# List of tracked leagues
LEAGUE_IDS = {
"Premier League": 39,
"La Liga": 140,
"Serie A": 135,
"Bundesliga": 78,
"Ligue 1": 61
}
Line-by-Line Explanation
API_KEY = "..."
Stores the API key needed to authenticate requests to the API-Football service. This key grants access to football data endpoints such as fixtures, teams, and standings.
API_BASE_URL = "https://v3.football.api-sports.io"
Defines the base URL for the API-Football service. All specific endpoints (e.g., `/fixtures`, `/teams`) will be appended to this base when sending requests.
HEADERS = {"x-apisports-key": API_KEY}
Prepares the headers to include the API key in each HTTP request. This is necessary for the API server to recognize and validate the client’s access.
LEAGUE_IDS = {...}
A dictionary mapping major football league names to their respective IDs in the API-Football database. These IDs are used when filtering requests (e.g., get data for the Premier League only).
Loading the Prediction Model and Initializing Flask
# ==========================
# Loading the model and scaler
# ==========================
MODEL_PATH = "model/predictionOfMatchResults.pkl"
SCALER_PATH = "model/scaler.pkl"
try:
model = joblib.load(MODEL_PATH)
print("✅ Model loaded successfully!")
except Exception as e:
print(f"❌ Error loading model: {e}")
model = None
try:
scaler = joblib.load(SCALER_PATH)
print("✅ Scaler loaded successfully!")
except Exception as e:
print(f"❌ Error loading scaler: {e}")
# If scaler is not available, use identity scaler
class IdentityScaler:
def transform(self, X):
return X
scaler = IdentityScaler()
# ==========================
# Flask Initialization
# ==========================
app = Flask(__name__)
Line-by-Line Explanation
MODEL_PATH = "..."
Defines the path to the serialized prediction model file (.pkl) that was trained and saved earlier.
SCALER_PATH = "..."
Sets the path to the saved scaler file used to normalize the features before making predictions.
try: joblib.load(MODEL_PATH)
Attempts to load the model from disk using joblib. If successful, the model is stored in memory.
except Exception as e:
If the model cannot be loaded, it prints the error and sets model to None to avoid application crashes.
try: joblib.load(SCALER_PATH)
Similar to the model loading block, but this time for the scaler file.
except Exception as e:
If loading the scaler fails, a custom fallback class IdentityScaler is defined and used. It simply returns the input as-is.
app = Flask(__name__)
Initializes a Flask application instance. This object will be used to define routes and launch the API server.
Season Management Functions
# ==========================
# Season management functions
# ==========================
def get_current_season():
today = datetime.today()
year = today.year
# If we are before August, the current season is the previous year
return year - 1 if today.month < 8 else year
def get_season_end(season):
# For a season starting in August, set the end to May 31 of the following year
return datetime(season + 1, 5, 31)
Line-by-Line Explanation
def get_current_season():
Defines a function that returns the current football season based on the current date.
today = datetime.today()
Retrieves the current date and time using the system’s clock.
year = today.year
Extracts the year from today’s date.
return year - 1 if today.month < 8 else year
Determines the football season:
- If the current month is **before August**, we consider the season as starting the **previous year**.
- Otherwise, we return the **current year**.
This logic aligns with most European leagues that start around August and end in May.
def get_season_end(season):
Defines a function that returns the end date of a given football season.
return datetime(season + 1, 5, 31)
Given a season year (e.g., 2023), this returns May 31 of the following year (2024), which is considered the season’s end date.
Function to Retrieve Upcoming Matches from the API
# ==========================
# Retrieve upcoming matches (for the coming week)
# ==========================
def get_upcoming_fixtures():
print("[DEBUG] Retrieving upcoming matches for the next 7 days...")
matches = []
today = datetime.today()
from_date = today.strftime('%Y-%m-%d')
to_date = (today + timedelta(days=7)).strftime('%Y-%m-%d')
current_season = get_current_season()
for league_name, league_id in LEAGUE_IDS.items():
print(f"[DEBUG] {league_name} (ID={league_id}), season {current_season} from {from_date} to {to_date}")
response = requests.get(
f"{API_BASE_URL}/fixtures",
headers=HEADERS,
params={
"league": league_id,
"season": current_season,
"from": from_date,
"to": to_date
}
).json()
if response and response.get("response"):
for fixture in response["response"]:
fixture_id = fixture["fixture"]["id"]
# Extract only the first 10 characters
date = fixture["fixture"]["date"][:10]
home_team = fixture["teams"]["home"]["name"]
away_team = fixture["teams"]["away"]["name"]
home_team_id = fixture["teams"]["home"]["id"]
away_team_id = fixture["teams"]["away"]["id"]
home_logo = fixture["teams"]["home"].get("logo", "")
away_logo = fixture["teams"]["away"].get("logo", "")
matches.append({
"league": league_name,
"league_id": league_id,
"fixture_id": fixture_id,
"date": date,
"home_team": home_team,
"away_team": away_team,
"home_team_id": home_team_id,
"away_team_id": away_team_id,
"home_logo": home_logo,
"away_logo": away_logo,
"season": current_season
})
else:
print(f"[DEBUG] No matches found for {league_name} (ID={league_id})")
return matches
Line-by-Line Explanation
def get_upcoming_fixtures():
Defines a function that retrieves football fixtures scheduled within the next 7 days.
today = datetime.today()
Gets the current system date.
from_date / to_date
These strings represent the date range used to filter fixtures: from today to 7 days later.
current_season = get_current_season()
Uses the helper function to determine the current season year.
for league_name, league_id in LEAGUE_IDS.items():
Iterates over the dictionary of tracked leagues to fetch matches for each.
requests.get(...)
Sends a GET request to the API-Football endpoint /fixtures, passing league, season, and date filters.
if response and response.get("response"):
Checks whether valid fixture data is returned.
for fixture in response["response"]:
Loops over each fixture received for the league.
fixture_id, date, home_team, away_team, etc.
Extracts important fields from each fixture, including team names, IDs, logos, and match date.
matches.append({...})
Adds each match’s data as a dictionary to the matches list.
return matches
Returns the complete list of upcoming fixtures found across all leagues.
Retrieve Team Fixtures Played Since the Start of the Season
# ==========================
# Get fixtures played by a team from the start of the season up to a given date
# ==========================
def get_team_fixtures(team_id, league_id, season, fixture_date):
url = f"{API_BASE_URL}/fixtures"
season_start = f"{season}-08-01"
params = {
"team": team_id,
"league": league_id,
"season": season,
"from": season_start,
"to": fixture_date,
"status": "FT" # Only finished matches
}
print(f"[DEBUG] GET request on {url} with params: {params}")
response = requests.get(url, headers=HEADERS, params=params).json()
print(f"[DEBUG] Raw response: {response.get('results', 0)} results.")
fixtures = []
if response and response.get("response"):
for fix in response["response"]:
fixtures.append(fix["fixture"]["id"])
return fixtures
Line-by-Line Explanation
def get_team_fixtures(team_id, league_id, season, fixture_date):
Defines a function to retrieve all matches played by a given team from the start of a season until a specified date.
url = f"{API_BASE_URL}/fixtures"
Constructs the API endpoint URL for retrieving fixtures data.
season_start = f"{season}-08-01"
Sets the start date of the season to August 1st of the given season year (most European football seasons start in August).
params = {...}
Prepares the query parameters for the GET request:
team: the team’s ID
league: the league’s ID
season: the season year
from: date from which to start retrieving fixtures
to: cutoff date for retrieval
status: only completed matches ("FT" stands for "Full Time")
requests.get(...)
Sends an HTTP GET request to the API with headers and parameters, and parses the response as JSON.
print(...)
Debug messages to trace the API request and how many results were returned.
fixtures = []
Initializes an empty list to store the IDs of the retrieved fixtures.
if response and response.get("response"):
Ensures the response contains valid data before attempting to process it.
for fix in response["response"]:
Iterates through each fixture returned in the API response.
fixtures.append(fix["fixture"]["id"])
Extracts the fixture ID and appends it to the list.
return fixtures
Returns the list of fixture IDs that match the filter criteria.
Retrieve Detailed Match Statistics for a Team
# ==========================
# Get detailed statistics for a given match (for a team)
# ==========================
def get_fixture_statistics(fixture_id, team_id):
url = f"{API_BASE_URL}/fixtures/statistics"
params = {"fixture": fixture_id, "team": team_id}
response = requests.get(url, headers=HEADERS, params=params).json()
if response and response.get("response") and len(response["response"]) > 0:
return response["response"][0].get("statistics", [])
return []
Line-by-Line Explanation
def get_fixture_statistics(fixture_id, team_id):
Defines a function that retrieves the detailed performance statistics for a given team in a specific match.
url = f"{API_BASE_URL}/fixtures/statistics"
Constructs the API endpoint URL specifically for fetching match statistics.
params = {"fixture": ..., "team": ...}
Prepares the GET request parameters:
fixture: ID of the match
team: ID of the team whose statistics are being requested
response = requests.get(...).json()
Sends a GET request to the API with authentication headers and query parameters, and parses the response as JSON.
if response and response.get("response") and len(response["response"]) > 0:
Checks that the response contains valid data and that the "response" array is not empty.
return response["response"][0].get("statistics", [])
Returns the list of statistics for the specified team. If "statistics" is missing, it returns an empty list by default.
return []
If the response is invalid or no statistics are found, the function returns an empty list.
Aggregate Statistics for a Team from Played Matches
# ==========================
# Aggregate statistics match by match (via /fixtures/statistics)
# ==========================
def aggregate_fixture_stats(team_id, league_id, season, fixture_date):
mapping = {
"Ball Possession": "possessionPct",
"Fouls": "foulsCommitted",
"Yellow Cards": "yellowCards",
"Red Cards": "redCards",
"Corner Kicks": "wonCorners",
"Goalkeeper Saves": "saves",
"Total Shots": "totalShots",
"Shots on Goal": "shotsOnTarget",
"Blocked Shots": "blockedShots",
"Total passes": "totalPasses",
"Passes accurate": "accuratePasses"
}
agg = {
"possessionPct_sum": 0.0,
"count_possession": 0,
"foulsCommitted": 0,
"yellowCards": 0,
"redCards": 0,
"wonCorners": 0,
"saves": 0,
"totalShots": 0,
"shotsOnTarget": 0,
"blockedShots": 0,
"totalPasses": 0,
"accuratePasses": 0
}
fixtures = get_team_fixtures(team_id, league_id, season, fixture_date)
if not fixtures:
print(f"[DEBUG] No fixture found for team {team_id} up to {fixture_date}.")
return agg
for fix_id in fixtures:
stats_list = get_fixture_statistics(fix_id, team_id)
for stat in stats_list:
stat_type = stat.get("type")
value = stat.get("value")
if value is None:
continue
if isinstance(value, str) and "%" in value:
try:
value = float(value.replace("%", ""))
except Exception:
value = 0.0
else:
try:
value = float(value)
except Exception:
value = 0.0
if stat_type in mapping:
key = mapping[stat_type]
if key == "possessionPct":
agg["possessionPct_sum"] += value
agg["count_possession"] += 1
else:
agg[key] += value
agg["possessionPct"] = (agg["possessionPct_sum"] / agg["count_possession"]) if agg["count_possession"] > 0 else 50.0
return agg
Line-by-Line Explanation
def aggregate_fixture_stats(...): Defines a function to calculate average statistics over all completed matches for a given team.
mapping = {...} Maps API stat labels (e.g., "Ball Possession") to normalized internal field names (e.g., "possessionPct").
agg = {...} Initializes an aggregation dictionary to hold cumulative stats across fixtures.
fixtures = get_team_fixtures(...) Retrieves a list of fixture IDs for the team up to the provided date.
if not fixtures: Returns the empty aggregation if no completed fixtures are found.
for fix_id in fixtures: Iterates over each played match.
stats_list = get_fixture_statistics(...) Retrieves detailed statistics for the match and team.
for stat in stats_list: Iterates over all statistics returned by the API for the match.
value = stat.get("value") Extracts the raw value of the stat.
if isinstance(value, str) and "%" in value: Converts percentages from string format (e.g., "58%") to float.
if stat_type in mapping: Checks if the stat type is one of the fields we're interested in.
if key == "possessionPct": Averages possession percentage separately to account for its format.
agg["possessionPct"] = ... Computes the final average possession if at least one value was found.
return agg Returns the aggregated stats for the team.
Retrieve Goal Statistics via API
# ==========================
# Retrieve goal statistics via /teams/statistics
# ==========================
def get_team_goals(team_id, league_id, season):
url = f"{API_BASE_URL}/teams/statistics"
params = {"team": team_id, "league": league_id, "season": season}
response = requests.get(url, headers=HEADERS, params=params).json()
goals = {"gf": 0.0, "ga": 0.0}
if response and response.get("response"):
resp = response["response"]
gf = resp.get("goals", {}).get("for", {}).get("total", {}).get("home", 0)
ga = resp.get("goals", {}).get("against", {}).get("total", {}).get("home", 0)
try:
goals["gf"] = float(gf)
goals["ga"] = float(ga)
except Exception:
goals["gf"] = 0.0
goals["ga"] = 0.0
return goals
Line-by-Line Explanation
def get_team_goals(team_id, league_id, season):
Defines a function to fetch a team’s goal statistics (goals scored and conceded at home) for a given league and season.
url = f"{API_BASE_URL}/teams/statistics"
Specifies the endpoint for accessing team statistics from the API-Football service.
params = {"team": ..., "league": ..., "season": ...}
Constructs the request parameters for identifying the correct team, league, and season.
response = requests.get(...).json()
Sends a GET request with authentication headers and parses the returned JSON response.
goals = {"gf": 0.0, "ga": 0.0}
Initializes a dictionary to hold the goal stats: goals for ("gf") and goals against ("ga").
if response and response.get("response"):
Ensures that a valid and non-empty response was received from the API.
resp = response["response"]
Stores the main response payload into a variable for easier access.
gf = resp.get("goals", {}).get("for", {}).get("total", {}).get("home", 0)
Safely retrieves the number of home goals scored ("goals for") by the team.
ga = resp.get("goals", {}).get("against", {}).get("total", {}).get("home", 0)
Safely retrieves the number of home goals conceded ("goals against") by the team.
try ... except
Tries to convert both values to float. If parsing fails, assigns a default value of 0.0.
return goals
Returns the dictionary containing the final goal statistics.
Build the Feature Vector for a Match
# ==========================
# Build the feature vector for a match
# ==========================
def process_match_data(fixture_id, home_team_id, away_team_id, league_id, season):
url = f"{API_BASE_URL}/fixtures"
params = {"id": fixture_id}
fix_data = requests.get(url, headers=HEADERS, params=params).json()
if not fix_data.get("response"):
print("[DEBUG] Fixture non trouvée.")
return None
fixture_date = fix_data["response"][0]["fixture"]["date"]
fixture_date_str = fixture_date[:10]
home_agg = aggregate_fixture_stats(home_team_id, league_id, season, fixture_date_str)
away_agg = aggregate_fixture_stats(away_team_id, league_id, season, fixture_date_str)
home_goals = get_team_goals(home_team_id, league_id, season)
away_goals = get_team_goals(away_team_id, league_id, season)
home_shotConversion = (home_agg["shotsOnTarget"] / home_agg["totalShots"]) if home_agg["totalShots"] > 0 else 0.0
away_shotConversion = (away_agg["shotsOnTarget"] / away_agg["totalShots"]) if away_agg["totalShots"] > 0 else 0.0
features = {
"leagueId": float(league_id),
"home_possessionPct": home_agg.get("possessionPct", 50.0),
"home_foulsCommitted": home_agg.get("foulsCommitted", 0.0),
"home_yellowCards": home_agg.get("yellowCards", 0.0),
"home_redCards": home_agg.get("redCards", 0.0),
"home_wonCorners": home_agg.get("wonCorners", 0.0),
"home_saves": home_agg.get("saves", 0.0),
"home_totalShots": home_agg.get("totalShots", 0.0),
"home_shotsOnTarget": home_agg.get("shotsOnTarget", 0.0),
"home_accuratePasses": home_agg.get("accuratePasses", 0.0),
"home_totalPasses": home_agg.get("totalPasses", 0.0),
"home_blockedShots": home_agg.get("blockedShots", 0.0),
"away_possessionPct": away_agg.get("possessionPct", 50.0),
"away_foulsCommitted": away_agg.get("foulsCommitted", 0.0),
"away_yellowCards": away_agg.get("yellowCards", 0.0),
"away_redCards": away_agg.get("redCards", 0.0),
"away_wonCorners": away_agg.get("wonCorners", 0.0),
"away_saves": away_agg.get("saves", 0.0),
"away_totalShots": away_agg.get("totalShots", 0.0),
"away_shotsOnTarget": away_agg.get("shotsOnTarget", 0.0),
"away_blockedShots": away_agg.get("blockedShots", 0.0),
"home_gf": home_goals.get("gf", 0.0),
"home_gd": home_goals.get("gf", 0.0) - home_goals.get("ga", 0.0),
"away_ga": away_goals.get("ga", 0.0),
"away_gd": away_goals.get("gf", 0.0) - away_goals.get("ga", 0.0),
"home_shotConversion": home_shotConversion,
"away_shotConversion": away_shotConversion
}
return features
Line-by-Line Explanation
- Defines a function
process_match_data to prepare a dictionary of features for a specific football match.
url = f"{API_BASE_URL}/fixtures": constructs the endpoint to fetch data about the fixture.
params = {"id": fixture_id}: prepares query parameters to retrieve the specific fixture using its ID.
fix_data = requests.get(...).json(): sends the request and parses the JSON response.
if not fix_data.get("response"):: checks if the match was found; otherwise returns None.
fixture_date = ...: extracts the full date-time of the fixture.
fixture_date_str = fixture_date[:10]: isolates the date in "YYYY-MM-DD" format.
home_agg = aggregate_fixture_stats(...): retrieves and aggregates match stats for the home team.
away_agg = aggregate_fixture_stats(...): does the same for the away team.
home_goals = get_team_goals(...): retrieves total and conceded goals for the home team.
away_goals = get_team_goals(...): same for the away team.
home_shotConversion = ...: calculates shot conversion ratio (shots on target / total shots) for the home team.
away_shotConversion = ...: same logic for the away team.
- All values (like possession, fouls, cards, passes, goals, etc.) are placed into a dictionary called
features.
return features: returns the complete feature vector for use in prediction.
Score Prediction Function
# ==========================
# Score prediction via model
# ==========================
def predict_match(fixture_id, home_team_id, away_team_id, league_id, season):
if model is None:
return {"error": "Model unavailable or not loaded."}
features = process_match_data(fixture_id, home_team_id, away_team_id, league_id, season)
if features is None:
return {"error": "Insufficient data or fixture not found."}
expected_features = [
"leagueId",
"home_possessionPct",
"home_foulsCommitted",
"home_yellowCards",
"home_redCards",
"home_wonCorners",
"home_saves",
"home_totalShots",
"home_shotsOnTarget",
"home_accuratePasses",
"home_totalPasses",
"home_blockedShots",
"away_possessionPct",
"away_foulsCommitted",
"away_yellowCards",
"away_redCards",
"away_wonCorners",
"away_saves",
"away_totalShots",
"away_shotsOnTarget",
"away_blockedShots",
"home_gf",
"home_gd",
"away_ga",
"away_gd",
"home_shotConversion",
"away_shotConversion"
]
ordered_features = {key: features.get(key, 0.0) for key in expected_features}
df_features = pd.DataFrame([ordered_features])
df_features[expected_features] = scaler.transform(df_features[expected_features])
print("[DEBUG] Features sent to the model:", df_features.iloc[0].to_dict())
prediction = model.predict(df_features)
score_home = int(prediction[0][0])
score_away = int(prediction[0][1])
return {"predicted_score": f"{score_home} - {score_away}"}
Line-by-Line Explanation
- Defines the function
predict_match to estimate the final score of a given match.
if model is None: checks if the ML model is available; returns an error message otherwise.
features = process_match_data(...): extracts features for the specified match using the helper function.
if features is None: returns an error if feature generation fails (e.g., missing stats).
expected_features = [...]: specifies the exact order and names of features expected by the model.
ordered_features = {...}: builds a dictionary of feature values with default 0.0 if missing.
df_features = pd.DataFrame([ordered_features]): converts the dictionary into a one-row DataFrame.
df_features[...] = scaler.transform(...): scales the features using the previously fitted scaler.
print(...): prints debug info showing the features passed to the model.
prediction = model.predict(df_features): uses the trained model to predict the home and away scores.
score_home = int(...) and score_away = int(...): converts predicted scores to integers.
return {"predicted_score": ...}: returns the score prediction as a string in "X - Y" format.
Flask Routes for Match Prediction
# ==========================
# Flask Routes
# ==========================
@app.route("/")
def index():
# Retrieve matches from the past week
matches = get_upcoming_fixtures()
return render_template("index.html", matches=matches)
@app.route("/predict", methods=["POST"])
def predict():
data = request.json
required_keys = ["fixture_id", "home_team_id", "away_team_id", "league_id", "season"]
missing = [k for k in required_keys if k not in data]
if missing:
return jsonify({"error": f"The following keys are missing: {', '.join(missing)}"}), 400
try:
season = int(data["season"])
except ValueError:
return jsonify({"error": "Season must be an integer."}), 400
result = predict_match(
data["fixture_id"],
data["home_team_id"],
data["away_team_id"],
data["league_id"],
season
)
return jsonify(result)
if __name__ == "__main__":
app.run(debug=True)
Line-by-Line Explanation
@app.route("/") : Defines the root URL of the application, corresponding to the home page.
def index(): : This is the function that handles requests to the home page.
get_upcoming_fixtures() : Retrieves upcoming matches for display.
render_template(...) : Renders the HTML template index.html and injects the list of matches.
@app.route("/predict", methods=["POST"]) : Defines a POST route for score prediction.
data = request.json : Retrieves the JSON payload sent by the client.
required_keys = [...]) : List of required fields expected in the JSON payload.
missing = [...] : Checks for missing keys in the JSON payload.
if missing: ... : If any key is missing, returns an error with HTTP status code 400.
try: season = int(...) : Ensures that the season is an integer, otherwise returns a 400 error.
predict_match(...) : Calls the prediction function with the data received.
return jsonify(result) : Returns the result (predicted score or error) as a JSON response.
if __name__ == "__main__": : Ensures this script runs only if executed directly.
app.run(debug=True) : Launches the Flask app in debug mode.